package es

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/olivere/elastic/v7"
	"log"
	"os"
	"time"
)

type EsService7 struct {
	es7 *elastic.Client
}

// CreateClient 创建一个客户端
func (self *EsService7) CreateClient() {
	// 1.创建客户端
	self.es7, _ = elastic.NewClient(
		elastic.SetURL("xxx"),
		//elastic.SetGzip(true),
		elastic.SetSniff(false), // 将sniff设置为false后，便不会自动转换地址
		elastic.SetHealthcheck(false),
		elastic.SetHealthcheckTimeout(10*time.Second),
		elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC", log.LstdFlags)), // 设置日志输出的名字
		elastic.SetInfoLog(log.New(os.Stdout, "", log.LstdFlags)),         // 输出日志级别
	)
}

func (self *EsService7) Query(boolQuery *elastic.BoolQuery, index string) (int64, []map[string]interface{}) {
	var searchResult, err = self.es7.Search(index).Query(boolQuery).Size(1).Do(context.Background())
	fmt.Println(err)
	total := searchResult.Hits.TotalHits.Value
	rs := make([]map[string]interface{}, total)
	for i, hit := range searchResult.Hits.Hits {
		str1 := string(hit.Source)
		var data map[string]interface{}
		json.Unmarshal([]byte(str1), &data)
		rs[i] = data
	}
	return total, rs
}

func (self *EsService7) DeleteByQuery(boolQuery *elastic.BoolQuery, index string) int64 {
	var searchResult, err = self.es7.DeleteByQuery(index).Query(boolQuery).Size(5000).Do(context.Background())
	fmt.Println(err)
	total := searchResult.Total
	fmt.Println(searchResult)
	return total
}

func (self *EsService7) AddFields(indexName string, fieldName string, fieldType string) {
	var map1, err = self.es7.GetMapping().Index(indexName).Do(context.Background())
	fmt.Println(err)
	properties := map1[indexName].(map[string]interface{})["mappings"].(map[string]interface{})["record"].(map[string]interface{})["properties"].(map[string]interface{})
	_, ok := properties[fieldName]
	if ok {
		// 字段已存在
		panic("字段" + fieldName + "已经存在了!")
	} else {
		// 添加字段
		type_field := make(map[string]interface{})
		new_field := make(map[string]interface{})
		new_field[fieldName] = type_field
		type_field["type"] = fieldType
		if fieldType == "Date" {
			type_field["format"] = "yyyy-MM-dd HH:mm:ss"
		}
		fmt.Println(new_field)
		mapping := make(map[string]interface{})
		mapping["properties"] = new_field
		fmt.Println("字段" + fieldName + "不存在,添加字段")
		a, err := self.es7.PutMapping().Index(indexName).BodyJson(mapping).Do(context.Background())
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(a)

	}
}
